import axios from "axios";
import {
	Message,
	Loading
} from "element-ui";
// import store from "../../store";
import {
	getToken
} from "./auth"; //获取到token
import md5 from "js-md5";
import {
	dateFormat
} from "./index";

function isNumber(obj) {
	return typeof obj === "number" && !isNaN(obj);
}

function isString(str) {
	return typeof str == "string" && str.constructor == String;
}

//创建一个axios实例
const service = axios.create({
	baseURL: process.env.VUE_APP_BASE_API,
	timeout: 300000,
	headers: {
		"Content-Type": "application/json;charset=utf-8",
	},
});

// 请求拦截器
service.interceptors.request.use(
	(config) => {
		const secretKey = "sdksdksdcfsd";
		const timeStamp = new Date().getTime() + "";
		let crypt = "";
		if (config.method === "get") {
			config.params = config.params ? config.params : {
				timeStamp
			};
			for (let key in config.params) {
				config.params[key] =
					config.params[key] || config.params[key] === 0 ?
					isNumber(config.params[key]) ?
					config.params[key] + "" :
					config.params[key] :
					"";
				if (isString(config.params[key])) {
					config.params[key] = config.params[key].trim();
				}
			}
			crypt = md5(JSON.stringify(config.params) + secretKey);
		} else {
			if (config.url === "/Sale/upload") {
				config.data.append("timeStamp", timeStamp);
				const params = {
					sizeLimit: config.data.get("sizeLimit"),
					riginalName: config.data.get("riginalName"),
					timeStamp,
				};
				crypt = md5(JSON.stringify({
					...params
				}) + secretKey);
			} else {
				config.data =
					config.data && JSON.stringify(config.data) !== "{}" ?
					config.data :
					{
						timeStamp
					};
				for (let key in config.data) {
					config.data[key] =
						config.data[key] || config.data[key] === 0 ?
						isNumber(config.data[key]) ?
						config.data[key] + "" :
						config.data[key] :
						"";
					if (isString(config.data[key])) {
						config.data[key] = config.data[key].trim();
					}
				}
				crypt = md5(JSON.stringify(config.data) + secretKey);
			}
		}
		config.headers["supplierCrypt"] = crypt;
		// let token = getToken(); //获取token

		let token = localStorage.getItem("token")
		if (token) {
			//每次请求都需要带上token去请求接口
			config.headers["SaleAuth"] = token;
		}
		return config;
	},
	(error) => {
		return Promise.reject(error);
	}
);

//响应拦截器
service.interceptors.response.use(
	(response, flag) => {
		console.log(flag);
		const noMsg = response.config.url === "/Supplier/Account/rechargeQuery";
		if (response.status === 200) {
			if (response.data.status === 200) {
				return Promise.resolve(response.data);
			} else {
				!noMsg && Message.error(response.data.msg);
				if (response.data.status === 300) {
					if (response.data.msg === '请登录') {
						if(window.location.origin=='http://localhost:8080'){
							location.href = 'http://localhost:8080/#/login'
						}else if(window.location.origin=='https://sale.doulaizuba.com')
						location.href = 'https://sale.doulaizuba.com/#/login'
					}
				}
				return Promise.reject(response);
			}
		} else {
			return Promise.reject(response);
		}

	},
	(error) => {
		switch (error.response.status) {
			case 405:
				Message.error(error.response.info);
				break;
			default:
				break;
		}
		return Promise.reject(error);
	}
);

export default {
	/**
	 * get方法，对应get请求
	 * @param {String} url [请求的url地址]
	 * @param {Object} params [请求时携带的参数]
	 * @param {Boolean} flag [是否弹出提示]
	 */
	get(url, params, flag) {
		return new Promise((resolve, reject) => {
			service
				.get('https://api.doulaizuba.com' + url, {
					params: params,
				})
				.then((res) => {
					if (flag && res.status === 200) {
						if (res.msg !== '获取成功') {
							Message.success(res.msg);
						}
					}
					resolve(res.data);
				})
				.catch((err) => {
					reject(err.data);
				});
		});
	},

	/**
	 * post方法，对应post请求
	 * @param {String} url [请求的url地址]
	 * @param {Object} params [请求时携带的参数]
	 * @param {Boolean} flag [是否弹出提示]
	 */
	post(url, params, flag) {
		return new Promise((resolve, reject) => {
			service
				.post('https://api.doulaizuba.com' + url, params)
				.then((res) => {
					if (flag && res.status === 200) {
						if (res.msg !== '获取成功') {
							Message.success(res.msg);
						}
					}
					resolve(res.data);
				})
				.catch((err) => {
					reject(err.data);
				});
		});
	},
	/**
	 * upload方法，对应upload post请求
	 * @param {String} url [请求的url地址]
	 * @param {Object} params [请求时携带的参数]
	 * @param {Boolean} flag [是否弹出提示]
	 */
	upload(url, params, flag) {
		return new Promise((resolve, reject) => {
			service
				.post(url, params, {
					headers: {
						"Content-Type": "multipart/form-data"
					},
				})
				.then((res) => {
					if (flag && res.status === 200) {
						Message.success(res.msg);
					}
					resolve(res.data);
				})
				.catch((err) => {
					reject(err.data);
				});
		});
	},
	/**
	 * export方法
	 * @param {String} url [请求的url地址]
	 * @param {Object} params [请求时携带的参数]
	 */
	export (url, params, name) {
		const loading = Loading.service({
			lock: true,
			text: "导出中。。。。。。",
			spinner: "el-icon-loading",
		});
		return new Promise((resolve, reject) => {
			const secretKey = "sdksdksdcfsd";
			const timeStamp = new Date().getTime() + "";
			const data =
				params && JSON.stringify(params) !== "{}" ? params : {
					timeStamp
				};
			for (let key in data) {
				data[key] =
					data[key] || data[key] === 0 ?
					isNumber(data[key]) ?
					data[key] + "" :
					data[key] :
					"";
				if (isString(data[key])) {
					data[key] = data[key].trim();
				}
			}
			const crypt = md5(JSON.stringify(data) + secretKey);
			axios
				.post(process.env.VUE_APP_BASE_API + url, params, {
					responseType: "blob",
					headers: {
						"Content-Type": "application/json",
						SaleAuth: getToken(),
						supplierCrypt: crypt,
					},
				})
				.then((res) => {
					const link = document.createElement("a");
					let blob = new Blob([res.data], {
						type: "application/vnd.ms-excel",
					});
					link.style.display = "none";
					link.href = URL.createObjectURL(blob);
					link.download = name + dateFormat(new Date()) + ".xls";
					document.body.appendChild(link);
					link.click();
					document.body.removeChild(link);
					loading.close();
					resolve(true);
				})
				.catch((err) => {
					loading.close();
					reject(err);
				});
		});
	},
};
